const { query } = require("../db/mysql");
const mock = require("mockjs");
async function queryUserByUsernameAndPassword(username, password) {
  const resp = await query(
    "select * from user where username = ? and password = ?",
    [username, password]
  );
  return resp[0];
}

async function queryUserByTel(tel) {
  const resp = await query("select * from user where tel = ?", [tel]);
  return resp[0];
}

async function queryUserByTelAndTelCode(tel, telCode) {
  const resp = await query("select * from user where tel = ? and telCode = ?", [
    tel,
    telCode,
  ]);
  return resp[0];
}

async function updateCodeByTel(tel, telCode) {
  const resp = await query(`UPDATE user SET telCode = ? WHERE tel = ?;`, [
    telCode,
    tel,
  ]);
  return resp;
}

async function insertDataToUser(tel, telCode) {
  const avatar = mock.mock("https://robohash.org/@id?set=set@integer(1,5)");
  const resp = await query(
    `INSERT INTO user (id, username, password, tel, telCode, nickname, avatar, createTime, sex, age) VALUES (NULL, NULL, NULL, ?, ?, '新用户', '${avatar}', CURRENT_TIMESTAMP, '男', 18);`,
    [tel, telCode]
  );
  return resp;
}

async function insertDataToUserByUsernameAndPassword(username, password) {
  const avatar = mock.mock("https://robohash.org/@id?set=set@integer(1,5)");
  const resp = await query(
    `INSERT INTO user (id, username, password, tel, telCode, nickname, avatar, createTime, sex, age) VALUES (NULL, ?, ?, null, null, '${mock.Random.cname()}', '${avatar}', CURRENT_TIMESTAMP, '男', 18);`,
    [username, password]
  );
  console.log(resp);
  return resp;
}

// state: 0  已下单 未支付 1 已支付,  未出行 2  已支付,  已出行  3  已取消（取消订单）

async function insertDataToOrderList({
  user_id,
  start,
  end,
  beginTime,
  endTime,
  title,
  price,
}) {
  const sql = `INSERT INTO orderList (id, user_id, start, end, beginTime, endTime, title, price, state) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, 0);`;
  return await query(sql, [
    user_id,
    start,
    end,
    beginTime,
    endTime,
    title,
    price,
  ]);
}

// 异步查询订单列表函数
async function queryOrderList() {
  // 定义查询语句
  const sql = `select * from orderList`;
  // 返回查询结果
  return await query(sql, [user_id]);
}

module.exports = {
  queryUserByUsernameAndPassword,
  queryUserByTel,
  updateCodeByTel,
  queryUserByTelAndTelCode,
  insertDataToUser,
  insertDataToOrderList,
  insertDataToUserByUsernameAndPassword,
  queryOrderList,
};
